import {
  getToken,
  setToken,
  setUser,
  getUser,
  removeToken,
  getRole,
  setRole
} from "@/utils/auth";
import { login, getUserInfo, logout } from "@/api/login";

const user = {
  state: {
    token: getToken(), //作为token的初始值，解决刷新后回到登录页面的问题
    user: getUser(),
    role: getRole()
  },
  mutations: {
    SET_TOKEN(state, token) {
      state.token = token;
      setToken(token);
    },
    SET_USER(state, user) {
      state.user = user;
      setUser(user);
    },
    SET_ROLE(state, role) {
      state.role = role;
      setRole(role);
    }
  },
  actions: {
    Login({ commit }, form) {
      return new Promise((resolve, reject) => {
        login(form.username.trim(), form.password)
          .then(resp => {
            const respData = resp.data;
            commit("SET_TOKEN", respData.data.token);
            commit("SET_ROLE", respData.data.role);
            resolve(respData);
          })
          .catch(error => {
            reject(error);
          });
      });
    },
    /**
     * 通过token获取用户信息
     */
    GetUserInfo({ commit }) {
      return new Promise((resolve, reject) => {
        console.log("GetUserinfo");
        getUserInfo()
          .then(resp => {
            const respData = resp.data;
            commit("SET_USER", respData.data);
            resolve(respData);
          })
          .catch(error => {
            reject(error);
          });
      });
    },
    //退出
    Logout({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token)
          .then(resp => {
            const respData = resp.data;
            commit("SET_TOKEN", "");
            commit("SET_ROLE", "");
            commit("SET_USER", "");
            removeToken();
            resolve(respData);
          })
          .catch(error => {
            reject(error);
          });
      });
    }
  }
};
export default user;
